import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:day03_flutter/pages/food_detail_page.dart'; // 导入详情页

class FoodPage extends StatefulWidget {
  const FoodPage({Key? key}) : super(key: key);

  @override
  State<FoodPage> createState() => _FoodPageState();
}

class _FoodPageState extends State<FoodPage> {
  final Dio _dio = Dio();
  List<dynamic> _foodCategories = [];
  bool _isLoading = false;
  String _errorMessage = '';

  @override
  void initState() {
    super.initState();
    _fetchFoodData();
  }

  // 获取美食数据
  Future<void> _fetchFoodData() async {
    setState(() {
      _isLoading = true;
      _errorMessage = '';
    });

    try {
      final response = await _dio.get('https://zhousg.atomgit.net/harmonyos-next/takeaway.json');
      
      setState(() {
        _foodCategories = response.data;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _errorMessage = '获取美食数据失败: ${e.toString()}';
        _isLoading = false;
      });
      
      // 错误处理
      if (context.mounted) {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('错误'),
            content: Text(_errorMessage),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('关闭'),
              ),
            ],
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '美食列表',
          style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
        ),
        centerTitle: true,
        elevation: 8,
      ),
      backgroundColor: Colors.grey[100],
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _errorMessage.isNotEmpty
              ? Center(child: Text(_errorMessage, style: const TextStyle(fontSize: 18)))
              : ListView.builder(
                  itemCount: _foodCategories.length,
                  itemBuilder: (context, categoryIndex) {
                    final category = _foodCategories[categoryIndex];
                    final foods = category['foods'] as List;
                    
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 分类标题
                        Padding(
                          padding: const EdgeInsets.fromLTRB(16, 20, 16, 10),
                          child: Text(
                            category['name'],
                            style: const TextStyle(
                              fontSize: 22,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        // 食品列表
                        ListView.builder(
                          physics: const NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemCount: foods.length,
                          itemBuilder: (context, foodIndex) {
                            final food = foods[foodIndex];
                            return _buildFoodItem(food);
                          },
                        ),
                      ],
                    );
                  },
                ),
    );
  }

  // 构建食品项
  Widget _buildFoodItem(dynamic food) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: InkWell(
        onTap: () {
          // 使用命名路由跳转到详情页
          Navigator.pushNamed(
            context,
            '/foodDetail',
            arguments: food,
          );
        },
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 食品图片
              ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.network(
                  food['picture'],
                  width: 100,
                  height: 100,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      width: 100,
                      height: 100,
                      color: Colors.grey[300],
                      child: const Icon(Icons.restaurant, size: 40),
                    );
                  },
                ),
              ),
              const SizedBox(width: 12),
              // 食品详情
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      food['name'],
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 6),
                    if (food['description'] != null && food['description'].toString().isNotEmpty)
                      Text(
                        food['description'],
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[600],
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    const SizedBox(height: 6),
                    Row(
                      children: [
                        Icon(Icons.thumb_up, size: 16, color: Colors.orange[400]),
                        const SizedBox(width: 4),
                        Text(
                          food['like_ratio_desc'] != null && food['like_ratio_desc'].toString().isNotEmpty
                              ? food['like_ratio_desc']
                              : '暂无评价',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey[600],
                          ),
                        ),
                        const SizedBox(width: 12),
                        Icon(Icons.shopping_bag, size: 16, color: Colors.blue[400]),
                        const SizedBox(width: 4),
                        Text(
                          '月售${food['month_saled']}',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '¥${food['price']}',
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.red,
                      ),
                    ),
                  ],
                ),
              ),
              // 添加一个箭头图标，提示可点击
              Icon(
                Icons.arrow_forward_ios,
                size: 16,
                color: Colors.grey[400],
              ),
            ],
          ),
        ),
      ),
    );
  }
}